from PIL import ImageFont

max_width = 0


def get_character_widths(font_path, font_size, characters):
    global max_width
    try:
        font = ImageFont.truetype(font_path, font_size)
        character_widths = {}

        for char in characters:
            width = int(font.getlength(char))
            character_widths[char] = width

            if max_width < width:
                max_width = width

        return character_widths
    except IOError as e:
        print(f"无法加载字体文件: {e}")
        return {}


def save_character_widths_to_file(character_widths, output_file):
    with open(output_file, 'w', encoding='utf-8') as file:
        for char, width in character_widths.items():
            file.write(f"{width / max_width},#{char}\n")


if __name__ == "__main__":
    # 设置字体文件路径和字体大小
    font_path_ = "MinecraftRegular-Bmg3.otf"  # 替换为你的 .otf 字体文件名
    font_size_ = 12

    # 定义要获取宽度的字符集合
    characters_ = [chr(i) for i in range(32, 128)]

    # 获取字符宽度
    character_width = get_character_widths(font_path_, font_size_, characters_)

    # 将结果保存到文件
    save_character_widths_to_file(character_width, "../character_widths.txt")
